/**
 * Created by Administrator on 2015/12/4.
 */
"use strict";
var _ = require('underscore');
var imgRule = require('../../../common/imgRule.js');
var F = require('../../../common/function');
var C = require('../../../config/index');

//validate mandatory organization fields according to organization
exports.validateOrganizationFields = function (obj, keys_array) {
  let error_msg = '';
  for (let p of keys_array) {
    if (typeof ( obj [p]) != " function ") {
      if (obj[p] == undefined || _.isEmpty(_.str.trim(obj[p]))) {
        error_msg += p + ' is undefined or empty,';
      }  else if (_.v.isIn(p, ['shopKeeperEmail'])) {//验证Email地址
        if (!_.v.isEmail(obj[p])) {
          error_msg += p + ' is not a valid email address,';
        }
      } else if (_.v.isIn(p, ['shopKeeperTel'])) {//验证是否为手机
        if (!_.v.isMobilePhone(obj[p], 'zh-CN')) {
          error_msg += p + ' is not a valid mobile phone number,';
        }
      } else if (_.v.isIn(p, ['loc', 'tel', 'image'])) {//验证经纬度
        if (!_.isArray(obj[p]) && p == 'tel') {
          error_msg += p + ' is not a valid array,';
        }
        if(p=='loc'){
          if (obj[p].length != 2) {
            error_msg += p + ' is not a valid array,';
          }
          for(let element of obj[p]){
            if (!_.v.isFloat(element)) {
              error_msg += p + ' is not a valid float,';
            }
          }
        }
      } else if (_.v.isIn(p, ['openTime', 'closeTime','vendorid'])) {//验证营业时间
        if (!_.v.isInt(obj[p])) {
          error_msg += p + ' is not valid integer,';
        }
      }
    }
  }
  if (error_msg != '') {
    error_msg += 'please check.';
  }
  return error_msg;
};

exports.generate_img_signature = function *(organization) {
  let signArr = [];
  if (organization.image && !_.isEmpty(organization.image)) {
    let imgStr = imgRule.id2imgStr('S', organization.id, 'jpg');
    let sign = yield F.getUpyunSignB(imgRule.str2imgURI(imgStr)[0]);
    sign.organizationid = organization.id;
    signArr.push(sign);
    organization.image = imgStr;
  }
  organization.upYunSign = signArr;
};

exports.getUpYunImage = function *(organization) {
  organization.image = _.str.trim(organization.image).length>0 ? imgRule.str2imgURI(organization.image)[0].imgURI + C.upyun.suffix : "";
};
exports.deleteUnuselessFields = function *(organization) {
  return organization = _.pick(organization, 'id', 'name', 'status', 'image', 'shopKeeperTel', 'shopKeeper', 'shopKeeperEmail', 'tel', 'authentication',
    'openTime', 'closeTime', 'vendorid', 'loc', 'address', 'graphicDetails', 'district');
};